package com.lekang.quartz.task;
import com.lekang.domain.OrderManagement;
import com.lekang.service.IOrderManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Component("orderTask")
public class OrderTask {
    private static final Logger log = LoggerFactory.getLogger(OrderTask.class);
    private static final long EXPIRE_MINUTES = 15; // 订单过期时间：15分钟

    @Autowired
    private IOrderManagementService orderManagementService;

    /**
     * 处理过期未支付订单：创建时间超过15分钟且交易状态为0时，修改为已关闭
     */
    @Transactional(rollbackFor = Exception.class) // 事务支持，异常时回滚
    public void updateExpiredOrderStatus() {
        try {
            // 优化方案1：查询时直接过滤条件（推荐，减少数据传输和处理量）
            // 需在service层添加带条件的查询方法，示例如下：
            // List<OrderManagement> expiredOrders = orderManagementService.selectExpiredUnpaidOrders(EXPIRE_MINUTES);

            // 兼容原查询方式（不推荐，效率低）：查询所有订单后过滤
            OrderManagement orderManagement = new OrderManagement();
            orderManagement.setTransactionStatus(0L);
            List<OrderManagement> allOrders = orderManagementService.selectOrderManagementList(orderManagement);
            for (OrderManagement order : allOrders) {
                // 1. 空值判断：跳过创建时间为空或交易状态不为0的订单
                if (order.getCreateTime() == null || order.getTransactionStatus() != 0) {
                    continue;
                }

                // 2. 计算创建时间与当前时间的差值（基于Java 8+ LocalDateTime，避免时区问题）
                LocalDateTime createLocalTime = convertDateToLocalDateTime(order.getCreateTime());
                LocalDateTime currentLocalTime = LocalDateTime.now();
                long timeDiffMinutes = Duration.between(createLocalTime, currentLocalTime).toMinutes();

                // 3. 超过15分钟则修改订单状态
                if (timeDiffMinutes > EXPIRE_MINUTES) {
                    order.setOrderStatus(5L); // 订单状态：已关闭
                    order.setTransactionStatus(2L); // 交易状态：已关闭
                    int updateCount = orderManagementService.updateOrderManagement(order);
                    log.info("订单[{}]因超时未支付被关闭，修改结果：{}行受影响", order.getOrderNo(), updateCount);
                }
            }
        } catch (Exception e) {
            log.error("处理过期订单状态失败", e);
            throw e; // 抛出异常触发事务回滚
        }
    }

    /**
     * Date 转 LocalDateTime（处理时区，避免时间偏差）
     */
    private LocalDateTime convertDateToLocalDateTime(Date date) {
        // 注意：根据系统实际时区调整，此处用默认时区，也可指定时区（如ZoneId.of("Asia/Shanghai")）
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}